﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class SponsorDAL : UKNowBaseDAL, IDALSponsor
    {
        private const string TBL_NAME               = "UKNOW_SPONSOR";
        private const string COL_LANG_ID            = "COL_LANG_ID";
        private const string COL_SPS_ID             = "COL_SPS_ID";
        private const string COL_SPS_NAME           = "COL_SPS_NAME";
        private const string COL_SPS_LOGO           = "COL_SPS_LOGO";
        private const string COL_SPS_DETAIL         = "COL_SPS_DETAIL";
        private const string COL_SPS_STATE          = "COL_SPS_STATE";
        private const string COL_SPS_ORDER          = "COL_SPS_ORDER";
        private const string COL_SPS_INSERT_TIME    = "COL_SPS_INSERT_TIME";
        private const string COL_SPS_UPDATE_TIME    = "COL_SPS_UPDATE_TIME";
        //mff
        private const string COL_SPS_HTML_PATH = "COL_SPS_HTML_PATH";
        private const string COL_SPS_TEMPLATE_ID = "COL_SPS_TEMPLATE_ID";
        private const string COL_SPS_COLUMN_ID = "COL_SPS_COLUMN_ID";
        private const string COL_SPS_LAYER_IDS = "COL_SPS_LAYER_IDS";
        //mff

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(SponsorModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_SPS_ID, DataType.Int)); } }
        
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_SPS_NAME, DataType.String, 200)); } }
        public IField LogoPath { get { return FieldFactory.Create(ModelType, "LogoPath", ColumnFactory.CreateColumn(COL_SPS_LOGO, DataType.String, 200)); } }
        public IField Detail { get { return FieldFactory.Create(ModelType, "Detail", ColumnFactory.CreateColumn(COL_SPS_DETAIL, DataType.NText)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_SPS_STATE, DataType.Int)); } }
        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_SPS_ORDER, DataType.Int)); } }
        //mff
        public IField ColumnID { get { return FieldFactory.Create(ModelType, "ColumnID", ColumnFactory.CreateColumn(COL_SPS_COLUMN_ID, DataType.Int)); } }
        public IField LayerIDs { get { return FieldFactory.Create(ModelType, "LayerIDs", ColumnFactory.CreateColumn(COL_SPS_LAYER_IDS, DataType.String, 200)); } }
        public IField HtmlFilePath { get { return FieldFactory.Create(ModelType, "HtmlFilePath", ColumnFactory.CreateColumn(COL_SPS_HTML_PATH, DataType.String, 200)); } }
        public IField TemplateID { get { return FieldFactory.Create(ModelType, "TemplateID", ColumnFactory.CreateColumn(COL_SPS_TEMPLATE_ID, DataType.Int)); } }
        //mff

        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_SPS_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_SPS_UPDATE_TIME, DataType.DateTime)); } }
        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, Name, LogoPath, Detail, State, Order, ColumnID, LayerIDs, TemplateID, HtmlFilePath, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return InsertFields; } }

        public SponsorDAL() { }

        public SponsorDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(SponsorModel model)
        {
            if (model == null) return;
        }

        #region IDALSponsor Members

        public SponsorModel GetSponsorModelByID(int? id)
        {
            if (!id.HasValue)
            { return null; }
            else
            {
                SponsorModel model = (SponsorModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
                SetForeignKeyModel(model);
                return model;
            }
        }

        public IList<SponsorModel> GetAllSponsorModels()
        {
            string whereClause = string.Format("where {0}={1}", COL_LANG_ID, (int)this.Language.LanguageType);
            List<SponsorModel> list = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<SponsorModel>().ToList();
            list.ForEach(new Action<SponsorModel>(SetForeignKeyModel));
            return list;
        }

        public IList<SponsorModel> GetPublishedSponsorModels()
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_SPS_STATE, 1, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            List<SponsorModel> list = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<SponsorModel>().ToList();
            list.ForEach(new Action<SponsorModel>(SetForeignKeyModel));
            return list;
        }

        public ResultInfo Save(SponsorModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_SPS_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将赞助商状态置为未发布
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "赞助商数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            } 
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存赞助商数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "赞助商数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除赞助商数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_SPS_ID, DataType.Int, ids));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "赞助商发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布赞助商时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_SPS_ID, DataType.Int, ids));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "赞助商取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布赞助商时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        #endregion
    }
}
